package com.yjps.system.controller;

import com.alibaba.fastjson.JSON;
import com.yjps.common.message.Message;
import com.yjps.common.page.Pager;
import com.yjps.common.util.ContantsUtil;
import com.yjps.system.model.Code;
import com.yjps.system.model.CodeType;
import com.yjps.system.service.CodeService;
import com.yjps.system.service.CodeTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 码表控制类
 * Created by jessy on 2015/8/22.
 */
@Controller
public class CodeController {

    Logger log = LoggerFactory.getLogger(CodeController.class);
    @Autowired
    CodeService codeService;
    @Autowired
    CodeTypeService codeTypeService;

    /**
     * 分页显示码表数据
     *
     * @param model
     * @param request  用于传递分页数据参数
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/system/code/list", method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Pager pager = codeService.getUserByPager(new Pager<Code>(request, response));
        List<Code> codeList = /*codeService.codeList();*/pager.getList();
        for (Code code : codeList) {
            CodeType ct = codeTypeService.findCodeType(code.getCodetypeId());
            code.setViewCodeType(ct.getCodetypeName());
        }
//        model.addAttribute("codeList",codeList);
        model.addAttribute(pager);
        return "system/basecode/codeList";
    }

    @RequestMapping(value = "/system/code/edit", method = RequestMethod.GET)
    public String editForm(Model model) {
        List<CodeType> codetypes = codeTypeService.codetypeList();
        if (codetypes != null) {
            model.addAttribute("codetypes", codetypes);
        }
        return "system/basecode/edit";
    }

    /**
     * 添加码表
     *
     * @param code
     * @param codetypeId  选择已存在的码表类
     * @param codetypeId2 自定义码表类
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/system/code/edit", method = RequestMethod.POST)
    public String edit(Code code, String codetypeId, String codetypeId2, HttpServletRequest request, Model model) {
        if (!StringUtils.isEmpty(codetypeId)) {
            if (codetypeId.equals("00")) {
                if (codetypeId2.equals("")) {

                    return "redirect:/system/code/edit";
                } else {
                    CodeType c = new CodeType();
                    c.setCodetypeName(codetypeId2);
                    c.setCodetypeState(1);
                    c.setIsValid(1);
                    c.setCodetypeDescription("");
                    int id = codeTypeService.addCodeType(c);
                    code.setCodetypeId(id);
                }
            } else {
                code.setCodetypeId(Integer.parseInt(codetypeId));
            }
            code.setIsValid(1);
            code.setCodeState(1);
            codeService.addCode(code);
            log.debug("add code success  id is " + code.getId());
        } else {
            log.debug("add code fail ");
        }
        return "redirect:/system/code/list";
    }

    /**
     * 更新码表
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/system/code/update", method = RequestMethod.POST)
    public String update(Code code) {

        codeService.updateCode(code);
        return "redirect:/system/code/list";
    }

    /**
     * 删除指定id的码表记录
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/system/code/delete", method = RequestMethod.GET)
    public String delete(@RequestParam(value = "id", required = true) String id, Model model) {
        Message message = null;
        codeService.deleteCode(Integer.parseInt(id));
        message = new Message(true, "delete successfully ");
        model.addAttribute("message", message);
        return "redirect:/system/code/list";
    }

    /**
     * 获得指定id的码表json对象
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/system/code/getCode", method = RequestMethod.GET)
    public String getCode(@RequestParam(value = "id", required = true) String id,HttpServletRequest request) {
        Code c = codeService.findCode(Integer.parseInt(id));
        CodeType ct = codeTypeService.findCodeType(c.getCodetypeId());
        Map map = (Map) request.getAttribute("map");
        if(map != null) {
            if (map.get(ct.getCodetypeName()) != null)
                c.setViewCodeType(map.get(ct.getCodetypeName()).toString());
        }else {
            c.setViewCodeType(ct.getCodetypeName());
        }
        String jsonString = JSON.toJSONString(c);
        System.out.println("code json string is " + jsonString);
        return jsonString;
    }

    /**
     * 公司前台获取区域码表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/company/code/getArea.do", method = RequestMethod.GET)
    public String findAreaCodeFront() {
        Message message = null;
        try {
            CodeType codeType = codeTypeService.findCodeTypeByName(ContantsUtil.CODETYPE_AREA);
            List<Code> codes = codeService.getCodeByType(codeType.getId());
            message = new Message(true,"获取区域码表",codes);
        }catch (Exception e){
            message = new Message(false,"获取失败");
        }
        System.out.println("message = " + message.toJson());
        return message.toJson();
    }

    /*@RequestMapping(value = "/company/upload",method = RequestMethod.POST)
    public String upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile orginalFile = (MultipartFile) multipartRequest
                .getFile("uploadfile");// 表单中对应的文件名；
        if (orginalFile != null && !orginalFile.isEmpty()) {// 如果有文章中带有附件
            String filename = orginalFile.getOriginalFilename();
            try {
                String path = request.getSession().getServletContext().getRealPath("");
                createDir(path + "/upload");
                path = path + "\\upload";
                System.out.println("path >>>>> " + path);
                String returnName = uploadMedia(orginalFile,path,"image");
                System.out.println("returnName = " + (path+"\\"+returnName));
request.getSession().setAttribute("Imageurl",returnName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "upload";
    }

    public String uploadMedia(MultipartFile file,String path,String type){
        log.debug("******上传多媒体文件******");
        int limitedSize=1024*1024*1024;
        String newFileName = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        switch(type)
        {
            case "image":limitedSize = 1024*1024;
                if(!(fileName.toLowerCase().endsWith(".jpg")))
                {
                    log.debug("******上传文件格式不正确，应为JPG格式******");
                    return "error:上传文件格式不正确，应为JPG格式";
                }
                break;
        }
        if(file.getSize()>limitedSize)
        {
            log.debug("******文件过大，应小于" + limitedSize + "B******");
            return "error:文件过大，应小于" + limitedSize/1024 + "KB";
        }
        String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length());
        newFileName += fileType;
        File targetFile = new File(path, newFileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFileName;
    }


    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if(dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败，目标目录已存在！");
            return false;
        }
        if(!destDirName.endsWith(File.separator))
            destDirName = destDirName + File.separator;
        // 创建单个目录
        if(dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "成功！");
            return false;
        }
    }*/
}
